const Koa = require('koa')
const body = require('koa-body')
const staticServ = require('koa-static')
const path = require('path')
const mongoose = require('mongoose')
const jwtAtuh = require('koa-jwt')

const conf = require('./conf')
mongoose.connect(conf.db)

const conn = mongoose.connection

conn.on('error', (err) => {
    throw err
})

conn.on('open', () => {
    console.log('数据库连接成功')
})

const app = new Koa()

app.use(body())
app.use(staticServ(path.join(__dirname, '/public')))

app.use(function(ctx, next){
    return next().catch((err) => {
      if (401 == err.status) {
        ctx.status = 401;
        ctx.body = 'Protected resource, use Authorization header to get access\n';
      } else {
        throw err;
      }
    });
  });

// 权限验证
app.use(jwtAtuh({
    secret: conf.secret
}).unless({
    path: [
        // 不需要校验的接口
        '/api/user/login'
    ]
}))

// 路由
const indexRouter = require('./routes/index')
const userRouter = require('./routes/user')
const orderRouter = require('./routes/order')

app.use(indexRouter.routes())
app.use(userRouter.routes())
app.use(orderRouter.routes())

app.listen(8081, () => {
    console.log('server is runging')
})
